<template>
  <Dialog v-model="dialogVisible" title="批量审核" width="1200px">
    <el-form
      ref="formRef"
      :model="batchAuditForm"
      :rules="batchAuditRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <!-- 筛选条件 -->
      <el-divider content-position="left">筛选条件</el-divider>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="评价计划">
            <el-select v-model="filterForm.planId" placeholder="请选择评价计划" @change="loadCandidates">
              <el-option label="2023年第四季度电工评价" value="1" />
              <el-option label="2023年第四季度焊工评价" value="2" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="申报职业">
            <el-select v-model="filterForm.professionId" placeholder="请选择申报职业" clearable>
              <el-option label="全部职业" value="" />
              <el-option label="电工" value="1" />
              <el-option label="焊工" value="2" />
              <el-option label="车工" value="3" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="审核状态">
            <el-select v-model="filterForm.auditStatus" placeholder="请选择审核状态" clearable>
              <el-option label="全部状态" value="" />
              <el-option label="待审核" :value="0" />
              <el-option label="审核通过" :value="1" />
              <el-option label="审核不通过" :value="2" />
              <el-option label="需补充材料" :value="3" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <!-- 批量操作 -->
      <el-divider content-position="left">批量操作</el-divider>
      <div style="margin-bottom: 15px;">
        <el-space>
          <el-button type="success" @click="batchApprove" :disabled="selectedCandidates.length === 0">
            批量通过 ({{ selectedCandidates.length }})
          </el-button>
          <el-button type="danger" @click="batchReject" :disabled="selectedCandidates.length === 0">
            批量拒绝
          </el-button>
          <el-button type="warning" @click="batchRequireMore" :disabled="selectedCandidates.length === 0">
            批量要求补充材料
          </el-button>
          <el-button @click="clearSelection">
            清空选择
          </el-button>
        </el-space>
      </div>
      
      <!-- 审核表单 -->
      <el-form-item label="批量审核结果" prop="batchAuditResult">
        <el-radio-group v-model="batchAuditForm.batchAuditResult">
          <el-radio :value="1">批量审核通过</el-radio>
          <el-radio :value="2">批量审核不通过</el-radio>
          <el-radio :value="3">批量要求补充材料</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item 
        label="不通过原因" 
        prop="batchRejectReasons" 
        v-if="batchAuditForm.batchAuditResult === 2"
      >
        <el-checkbox-group v-model="batchAuditForm.batchRejectReasons">
          <el-checkbox label="identity">身份信息不符</el-checkbox>
          <el-checkbox label="qualification">学历资格不符</el-checkbox>
          <el-checkbox label="experience">工作经验不足</el-checkbox>
          <el-checkbox label="materials">材料不完整</el-checkbox>
          <el-checkbox label="fake">材料造假</el-checkbox>
          <el-checkbox label="other">其他原因</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      
      <el-form-item 
        label="需补充材料" 
        prop="batchRequiredMaterials" 
        v-if="batchAuditForm.batchAuditResult === 3"
      >
        <el-checkbox-group v-model="batchAuditForm.batchRequiredMaterials">
          <el-checkbox label="idCard">身份证</el-checkbox>
          <el-checkbox label="diploma">学历证书</el-checkbox>
          <el-checkbox label="workCert">工作证明</el-checkbox>
          <el-checkbox label="skillCert">技能证书</el-checkbox>
          <el-checkbox label="photo">照片</el-checkbox>
          <el-checkbox label="other">其他材料</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      
      <el-form-item label="批量审核说明" prop="batchComments">
        <el-input
          v-model="batchAuditForm.batchComments"
          type="textarea"
          :rows="3"
          placeholder="请输入批量审核说明"
        />
      </el-form-item>
    </el-form>
    
    <!-- 候选人列表 -->
    <el-divider content-position="left">候选人列表</el-divider>
    <el-table 
      ref="tableRef"
      :data="candidateList" 
      border 
      style="width: 100%"
      @selection-change="handleSelectionChange"
      max-height="400"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="candidateName" label="考生姓名" width="120" />
      <el-table-column prop="idCard" label="身份证号" width="180" />
      <el-table-column prop="professionName" label="申报职业" width="120" />
      <el-table-column prop="skillLevel" label="申报等级" width="100">
        <template #default="{ row }">
          {{ getLevelName(row.skillLevel) }}
        </template>
      </el-table-column>
      <el-table-column prop="submitTime" label="申报时间" width="150" />
      <el-table-column prop="auditStatus" label="当前状态" width="120">
        <template #default="{ row }">
          <el-tag :type="getAuditStatusColor(row.auditStatus)">
            {{ getAuditStatusName(row.auditStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="materialCompleteness" label="材料完整度" width="120">
        <template #default="{ row }">
          <el-progress 
            :percentage="row.materialCompleteness" 
            :color="getCompletenessColor(row.materialCompleteness)"
            :stroke-width="8"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="{ row }">
          <el-button link type="primary" size="small" @click="viewCandidate(row)">
            查看详情
          </el-button>
          <el-button link type="success" size="small" @click="quickApprove(row)">
            快速通过
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 统计信息 -->
    <el-divider content-position="left">统计信息</el-divider>
    <el-row :gutter="20" style="margin-bottom: 20px;">
      <el-col :span="6">
        <el-statistic title="总申请数" :value="statisticsData.totalCount" />
      </el-col>
      <el-col :span="6">
        <el-statistic title="待审核" :value="statisticsData.pendingCount" value-style="color: #e6a23c" />
      </el-col>
      <el-col :span="6">
        <el-statistic title="已通过" :value="statisticsData.approvedCount" value-style="color: #67c23a" />
      </el-col>
      <el-col :span="6">
        <el-statistic title="未通过" :value="statisticsData.rejectedCount" value-style="color: #f56c6c" />
      </el-col>
    </el-row>
    
    <template #footer>
      <el-button @click="submitBatchAudit" type="primary" :loading="formLoading">
        提交批量审核
      </el-button>
      <el-button @click="exportAuditReport">
        导出审核报告
      </el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'

const emit = defineEmits(['success'])
const dialogVisible = ref(false)
const formLoading = ref(false)
const formRef = ref()
const tableRef = ref()

const filterForm = ref({
  planId: '',
  professionId: '',
  auditStatus: ''
})

const batchAuditForm = ref({
  batchAuditResult: undefined,
  batchRejectReasons: [] as string[],
  batchRequiredMaterials: [] as string[],
  batchComments: ''
})

const batchAuditRules = ref({
  batchAuditResult: [{ required: true, message: '请选择批量审核结果', trigger: 'change' }],
  batchComments: [{ required: true, message: '批量审核说明不能为空', trigger: 'blur' }]
})

const selectedCandidates = ref([])
const candidateList = ref([
  {
    id: '1',
    candidateName: '张三',
    idCard: '123456789012345678',
    professionName: '电工',
    skillLevel: 3,
    submitTime: '2023-12-01 10:00:00',
    auditStatus: 0,
    materialCompleteness: 85
  },
  {
    id: '2',
    candidateName: '李四',
    idCard: '123456789012345679',
    professionName: '焊工',
    skillLevel: 2,
    submitTime: '2023-12-01 11:00:00',
    auditStatus: 0,
    materialCompleteness: 92
  },
  {
    id: '3',
    candidateName: '王五',
    idCard: '123456789012345680',
    professionName: '车工',
    skillLevel: 4,
    submitTime: '2023-12-01 12:00:00',
    auditStatus: 1,
    materialCompleteness: 100
  }
])

const statisticsData = computed(() => {
  const totalCount = candidateList.value.length
  const pendingCount = candidateList.value.filter(c => c.auditStatus === 0).length
  const approvedCount = candidateList.value.filter(c => c.auditStatus === 1).length
  const rejectedCount = candidateList.value.filter(c => c.auditStatus === 2).length
  
  return { totalCount, pendingCount, approvedCount, rejectedCount }
})

const getLevelName = (level: number) => {
  const levelMap = { 1: '初级', 2: '中级', 3: '高级', 4: '技师', 5: '高级技师' }
  return levelMap[level] || '-'
}

const getAuditStatusName = (status: number) => {
  const statusMap = { 0: '待审核', 1: '审核通过', 2: '审核不通过', 3: '需补充材料' }
  return statusMap[status] || '-'
}

const getAuditStatusColor = (status: number) => {
  const colorMap = { 0: 'warning', 1: 'success', 2: 'danger', 3: 'info' }
  return colorMap[status] || 'info'
}

const getCompletenessColor = (percentage: number) => {
  if (percentage >= 90) return '#67c23a'
  if (percentage >= 70) return '#e6a23c'
  return '#f56c6c'
}

const handleSelectionChange = (selection: any[]) => {
  selectedCandidates.value = selection
}

const batchApprove = () => {
  if (selectedCandidates.value.length === 0) {
    ElMessage.warning('请先选择要操作的考生')
    return
  }
  
  batchAuditForm.value.batchAuditResult = 1
  batchAuditForm.value.batchComments = `批量通过 ${selectedCandidates.value.length} 名考生的申请`
}

const batchReject = () => {
  if (selectedCandidates.value.length === 0) {
    ElMessage.warning('请先选择要操作的考生')
    return
  }
  
  batchAuditForm.value.batchAuditResult = 2
  batchAuditForm.value.batchComments = `批量拒绝 ${selectedCandidates.value.length} 名考生的申请`
}

const batchRequireMore = () => {
  if (selectedCandidates.value.length === 0) {
    ElMessage.warning('请先选择要操作的考生')
    return
  }
  
  batchAuditForm.value.batchAuditResult = 3
  batchAuditForm.value.batchComments = `要求 ${selectedCandidates.value.length} 名考生补充材料`
}

const clearSelection = () => {
  tableRef.value?.clearSelection()
}

const loadCandidates = () => {
  // TODO: 根据筛选条件加载候选人
  console.log('加载候选人列表', filterForm.value)
}

const viewCandidate = (candidate: any) => {
  // TODO: 查看候选人详情
  console.log('查看候选人详情:', candidate)
}

const quickApprove = (candidate: any) => {
  candidate.auditStatus = 1
  ElMessage.success(`${candidate.candidateName} 快速通过审核`)
}

const submitBatchAudit = async () => {
  if (selectedCandidates.value.length === 0) {
    ElMessage.warning('请先选择要审核的考生')
    return
  }
  
  const elForm = formRef.value
  if (!elForm) return
  const valid = await elForm.validate()
  if (!valid) return
  
  formLoading.value = true
  try {
    const auditData = {
      candidateIds: selectedCandidates.value.map(c => c.id),
      auditResult: batchAuditForm.value.batchAuditResult,
      rejectReasons: batchAuditForm.value.batchRejectReasons,
      requiredMaterials: batchAuditForm.value.batchRequiredMaterials,
      comments: batchAuditForm.value.batchComments
    }
    
    // TODO: 提交批量审核
    console.log('提交批量审核:', auditData)
    
    // 更新本地状态
    selectedCandidates.value.forEach(candidate => {
      candidate.auditStatus = batchAuditForm.value.batchAuditResult
    })
    
    dialogVisible.value = false
    emit('success')
    ElMessage.success(`成功审核 ${selectedCandidates.value.length} 名考生`)
  } finally {
    formLoading.value = false
  }
}

const exportAuditReport = () => {
  // TODO: 导出审核报告
  ElMessage.info('审核报告导出功能开发中...')
}

const resetForm = () => {
  filterForm.value = {
    planId: '',
    professionId: '',
    auditStatus: ''
  }
  
  batchAuditForm.value = {
    batchAuditResult: undefined,
    batchRejectReasons: [],
    batchRequiredMaterials: [],
    batchComments: ''
  }
  
  selectedCandidates.value = []
  
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

const open = () => {
  dialogVisible.value = true
  resetForm()
}

defineExpose({ open })
</script> 